import fs from 'fs'
import { reflectDesc } from './mysqlreflect.js'
import { formatToHump, formatToUpHump } from './utils.js'
export const createComposable = (columns, tableName) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err

    const config = JSON.parse(data)
    const humpTableName = formatToHump(tableName)
    const folder = `${config.vendorFolder}/${humpTableName}`
    // verify file is exist or not
    const composable = `${folder}/${humpTableName}.ts` // 添加组合函数
    if (fs.existsSync(composable)) {
      // file is exist
      console.log(`======file is existed and ignored to created composable:${composable}=======`)
    } else {
      // file is not exist
      if (!fs.existsSync(folder)) {
        fs.mkdirSync(folder, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      fs.writeFileSync(composable, getContent(tableName, columns), { flag: 'a' }, (err) => {
        if (err) {
          console.log('========error======')
          throw err
        } else {
          console.log(`======succeessfully created composable:${composable}=======`)
        }
      })
    }
  })
}


const getContent = (tableName, columns) => {
  const humpTableName = formatToHump(tableName)
  const humpUpTableName = formatToUpHump(tableName)
  const tableHeaders = []
  const filters = {} // 过滤器  filters直接绑定到组合函数中不另做处理
  let imports = []
  columns.map(item => {
    if (item.isResearch && !item.isKeyword){
      // 加入搜索
      let value = ''
      switch (item.dataType) {
        case 'tinyint':
        case 'bigint':
        case 'smallint':
        case 'mediumint':
        case 'int':
        case 'float':
        case 'double':
        case 'decimal':
          value = 0; break;
        case 'char':
        case 'varchar':
        case 'set':
        case 'enum':
        case 'text':
        case 'mediumtext':
        case 'longtext':
        case 'datetime':
        case 'date':
        case 'timestamp':
          value = ''; break;
      }
      filters[item.columnName] = value
    }
    const desc = reflectDesc(item)
    let obj = {
      headerName: desc,
      field: item.columnName   // 选择绑定的名称
    }
    tableHeaders.push(obj)
  })
  filters['keywords'] = ''
  return `
import { model,Form } from './form'
import { ref,reactive,watch } from 'vue'
import { Header } from '@/components/table/table'
import { add, del, update, get,list } from './restful'
${imports.join('\n')}
export const Get${humpUpTableName} = () => {
  const initData:Form = model
  const ${humpTableName}Filters = reactive(${JSON.stringify(filters)})
  const ${humpTableName}Total = ref(0)
  const ${humpTableName} = ref(initData)
  const ${humpTableName}Columns: Array<Header> = ${JSON.stringify(tableHeaders)}
  const listIni: Array<any> = []
  const ${humpTableName}Page = ref(1)
  const ${humpTableName}Size = ref(10)
  let ${humpTableName}List = ref(listIni)
  const get${humpUpTableName} = (calBack:Function = () => {}) => {
    get(${humpTableName}.value.${tableName}_id).then((res:any) => {
      ${humpTableName}.value = res.data
      calBack.apply(null)
    }).catch(() => {})
  }
  const add${formatToUpHump(tableName)} = (calBack:Function = () => {}) => {
    add(${humpTableName}.value).then((res:any) => { calBack.apply(null) }).catch(() => {})
  }
  const update${humpUpTableName} = (calBack:Function = () => {}) => {
    update(${humpTableName}.value).then((res:any) => { calBack.apply(null) }).catch(() => {})
  }
  const del${humpUpTableName} = (calBack:Function = () => {}) => {
    del(${humpTableName}.value.${tableName}_id).then((res:any) => { calBack.apply(null) }).catch(() => {})
  }
  const list${humpUpTableName} = (calBack:Function=()=>{}) => {
    ${humpTableName}List.value.splice(0, ${humpTableName}List.value.length)
    list(Object.assign({page:${humpTableName}Page.value,size:${humpTableName}Size.value},${humpTableName}Filters)).then((res:any) => {
    ${humpTableName}List.value = res.data.list;
    ${humpTableName}Total.value = res.data.count
    ${humpTableName}Page.value += 1
    calBack.apply(null) }).catch(() => {})
  }
  watch(${humpTableName}Filters, () => {
    ${humpTableName}Page.value = 1
    list${humpUpTableName}()
  })


  return {
    ${humpTableName},
    get${humpUpTableName},
    add${humpUpTableName},
    update${humpUpTableName},
    del${humpUpTableName},
    list${humpUpTableName},
    ${humpTableName}Total,
    ${humpTableName}List,
    ${humpTableName}Page,
    ${humpTableName}Size,
    ${humpTableName}Columns,
    ${humpTableName}Filters
  }
}

`
}
